package com.mechat.ui.chats

import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.custom.base.config.BaseConfig
import com.custom.base.entity.OkHttpBodyEntity
import com.custom.base.http.OkHttpFromBoy
import com.custom.base.http.OkHttpManager
import com.custom.base.http.SDOkHttpResoutCallBack
import com.custom.base.mvp.MVPBaseFragment
import com.gyf.immersionbar.ImmersionBar
import com.mechat.Constant
import com.mechat.R
import com.mechat.adapter.MyPagerAdapter
import com.mechat.entity.ChatsModelEntity
import com.mechat.rongyun.RongConfigUtil
import com.mechat.ui.chats.item.ItemFragment
import com.mechat.util.HttpRequest
import com.mechat.view.CustomViewPager
import com.mechat.view.tablayout.SlidingTabLayout
import com.mechat.view.tablayout.listener.OnTabSelectListener
import com.sunday.eventbus.SDBaseEvent
import com.sunday.eventbus.SDEventManager
import io.rong.imkit.SpName
import io.rong.imkit.event.EnumEventTag
import io.rong.imkit.userinfo.RongUserInfoManager
import io.rong.imlib.model.UserInfo
import kotlinx.android.synthetic.main.frag_chats.*
import java.util.Timer
import java.util.TimerTask


class ChatsFragment : MVPBaseFragment<ChatsContract.View, ChatsPresenter>(), ChatsContract.View {

    private val mFragments = ArrayList<Fragment>()
    private var timer: Timer? = null
    private val handler: Handler = Handler(Looper.getMainLooper())
    override fun bindLayout(): Int {
        return R.layout.frag_chats
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        getData()
        // 创建一个5秒轮询的定时器
        timer = Timer()
        timer?.schedule(object : TimerTask() {
            override fun run() {
                // 在这里添加你需要周期性执行的代码
                refreshData()
            }
        }, 5000, 5000) // 首次执行延迟5000毫秒，之后每5000毫秒执行一次
        ImmersionBar.with(this)
            .statusBarColor("#4699FF")
            .statusBarDarkFont(false)
            .init()
    }

    private fun refreshData() {
        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setPost(Constant.chat_model_list_url)
                requestBody.add(
                    "chatterUserCode",
                    BaseConfig.getInstance.getString(SpName.userCode, "")
                )
                requestBody.add("timer", true)
            }
        }, object : SDOkHttpResoutCallBack<ChatsModelEntity>() {
            override fun onSuccess(entity: ChatsModelEntity) {
                if (entity.data != null) {
                    for (i in 0 until entity.data.modelList.size) {
                        chatsTableLayout.showMsg(
                            i,
                            entity.data.modelList[i].modelAccount.unReadNum
                        )
                    }
                    SDEventManager.post(
                        entity.data.totalUnReadNum,
                        EnumEventTag.REFRESH_CHAT_SIZE.ordinal
                    )
                }
            }

            override fun onFailure(code: Int, msg: String) {

            }
        })
    }

    private fun getData() {
        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setPost(Constant.chat_model_list_url)
                requestBody.add(
                    "chatterUserCode",
                    BaseConfig.getInstance.getString(SpName.userCode, "")
                )
            }
        }, object : SDOkHttpResoutCallBack<ChatsModelEntity>() {
            override fun onSuccess(entity: ChatsModelEntity) {
                val mTitles = arrayListOf<String>()
                val mImages = arrayListOf<String>()

                for (i in 0 until entity.data.modelList.size) {
                    mTitles.add(entity.data.modelList[i].modelAccount.nickName)
                    mImages.add(entity.data.modelList[i].modelAccount.avatarUrl)
                    val element = ItemFragment()
                    val bundle = Bundle()
                    bundle.putString(
                        "modelUserCode",
                        entity.data.modelList[i].modelAccount.userCode
                    )
                    element.arguments = bundle
                    mFragments.add(element)

                    RongUserInfoManager.getInstance()
                        .refreshUserInfoCache(
                            UserInfo(
                                entity.data.modelList[i].modelAccount.userCode,
                                entity.data.modelList[i].modelAccount.nickName,
                                Uri.parse(entity.data.modelList[i].modelAccount.avatarUrl)
                            )
                        )
                }
                val mAdapter = MyPagerAdapter(
                    fragmentManager!!, mFragments
                )
                chatsVp.adapter = mAdapter
                chatsTableLayout.setViewPager(chatsVp, mTitles, mImages)

                entity.data.modelList[0].modelAccount.token?.let {
                    RongConfigUtil.connectIM(
                        it,
                        entity.data.modelList[0].modelAccount.userCode
                    )
                }
                BaseConfig.getInstance.setString(
                    SpName.modelUserCode,
                    entity.data.modelList[0].modelAccount.userCode
                )
                for (i in 0 until entity.data.modelList.size) {
                    if (entity.data.modelList[i].modelAccount.unReadNum > 0) {
                        chatsTableLayout.showMsg(i, entity.data.modelList[i].modelAccount.unReadNum)
                    }
                }

                chatsTableLayout.setOnTabSelectListener(object : OnTabSelectListener {
                    override fun onTabSelect(position: Int) {
                        entity.data.modelList[position].modelAccount.token?.let { it1 ->
                            RongConfigUtil.connectIM(
                                it1, entity.data.modelList[position].modelAccount.userCode
                            )
                            BaseConfig.getInstance.setString(
                                SpName.modelUserCode,
                                entity.data.modelList[position].modelAccount.userCode
                            )
                            HttpRequest.commonNotify("ModelTable",entity.data.modelList[position].modelAccount.nickName)

                        }

                    }

                    override fun onTabReselect(position: Int) {
                    }

                })
                SDEventManager.post(
                    entity.data.totalUnReadNum,
                    EnumEventTag.REFRESH_CHAT_SIZE.ordinal
                )
            }

            override fun onFailure(code: Int, msg: String) {

            }
        })
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            ImmersionBar.with(this)
                .statusBarColor("#4699FF")
                .statusBarDarkFont(false)
                .init()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (timer != null) {
            timer?.cancel()
        }
    }

    override val chatsTableLayout: SlidingTabLayout
        get() = chats_table_layout
    override val chatsVp: CustomViewPager
        get() = chats_vp
    override val chatsTitle: TextView
        get() = chats_title

}